﻿using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace LightLibrary {
	public partial class FormLibraryOpen : Form {
		// === Private ================================================================================================
		public LibraryBase OpenedLibrary { get; private set; }

		public FormLibraryOpen() {
			InitializeComponent();
			InitOpenView();
		}

		// === Private ================================================================================================
		private readonly Dictionary<DataGridViewRow, string> _libNamesByRow = new Dictionary<DataGridViewRow, string>();

		private void InitOpenView() {
			foreach(var libName in Library.Instance.GetLibNames()) {
				var row = TableTools.CreateRowForBooks(openView, libName);
				openView.Rows.Add(row);
				_libNamesByRow.Add(row, libName);
			}
			if(_libNamesByRow.Keys.Count == 0) {
				btnOpen.Enabled = false;
			}
		}

		private void btnOpenClick(object sender, System.EventArgs e) {
			if(openView.SelectedCells.Count != 1) {
				MessageBox.Show("Must be select only one row");
				return;
			}
			var selectedRow = openView.Rows[openView.SelectedCells[0].RowIndex];
			var libName = _libNamesByRow[selectedRow];
			if(Library.Instance.Work != null && Library.Instance.Work.LibName == libName) {
				Library.Instance.Save();
				MessageBox.Show("Already opened");
				return;
			}
			var libModelFileInfo = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), libName + ".xml"));
			OpenedLibrary = Factory.CreateLibrary(XmlTools.GetLibModel(libModelFileInfo.FullName));
			Close();
		}

		private void btnCancelClick(object sender, System.EventArgs e) {
			Close();
		}

		private void openViewDoubleClick(object sender, System.EventArgs e) {
			btnOpenClick(sender, e);
		}
	}
}